# -*- coding: utf-8 -*-
# @Time : 2022-05-23 17:20
# @Author : Z
# @Function :

import os

import pytest
from Common.Excel.excel import get_reader, get_writer
from Common.Logger import logger
from Keywords.app_keys import App


class Conf:

    def __init__(self):
        self.cases = []
        self.obj = App()
        self.feature = ''
        self.feature_idx = 0
        self.story = ''
        self.story_idx = 0
        self.name = 'app'
        self.last_story = self.name
        self.writer = None

    def runCase(self, case_path='', result_path=''):
        reader = get_reader(case_path)
        self.writer = get_writer(case_path, result_path)
        sheetname = reader.get_sheets()
        for sheet in sheetname:
            self.feature = sheet
            self.feature_idx += 1
            self.story_idx = 0
            reader.set_sheet(sheet)
            self.writer.set_sheet(sheet)
            lines = reader.readline()
            case = []
            for i in range(1, len(lines)):
                line = lines[i]
                # 如果是模块
                if len(line[0]) > 1:
                    if case:
                        self.cases.append(case)
                        case = []
                    # 执行模块所有的用例
                    if self.cases:
                        # print('执行')
                        self.__run_pytest()
                    self.story = line[0]
                    self.story_idx += 1
                    self.writer.row = i
                # 如果是用例名
                elif len(line[1]) > 1:
                    if case:
                        self.cases.append(case)
                        case = []
                    case.append(line)
                # 如果是步骤
                else:
                    case.append(line)

            if case:
                self.cases.append(case)

            if self.cases:
                # print('执行')
                self.__run_pytest()

        self.obj.quit()
        self.obj.kill_appium()
        self.writer.save_close()
        os.rename('./ddt/test_%s.py' % self.story, './ddt/test_%s.py' % self.name)

    def __run_pytest(self):
        logger.info(self.cases)
        os.rename('./ddt/test_%s.py' % self.last_story, './ddt/test_%s.py' % self.story)
        self.last_story = self.story
        pytest.main(['-s', './ddt/test_%s.py' % self.story, '--alluredir', './result'])
        self.cases.clear()


conf = Conf()
